package it.giuseppetrisciuoglio.lyrics.service.facebook;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.restfb.*;
import com.restfb.types.Post;

@Service
public class FacebookService {
	
	@Value("${proxy.enabled}")
	private boolean proxyEnabled;
	
	@Autowired
	private ProxyWebRequestor proxyWebRequestor;
	
	private final transient Logger log = LoggerFactory.getLogger(getClass());
	
	public String getYoutubeURL(String artista, String titolo){
		log.debug("getYoutubeURL(): artista={}, titolo={}", artista, titolo);
		FacebookClient publicOnlyFacebookClient = null;
		if (!proxyEnabled){
			publicOnlyFacebookClient = new DefaultFacebookClient();
		}else{
			publicOnlyFacebookClient = new DefaultFacebookClient(null, proxyWebRequestor, new DefaultJsonMapper());
		}

		Connection<Post> publicSearch = publicOnlyFacebookClient.fetchConnection("search", Post.class,
				    Parameter.with("q", artista+" "+titolo), Parameter.with("type", "post"));
		List<Post> posts = publicSearch.getData();
		if (posts != null){
			for (Post post : posts) {
				if (post.getLink()!=null && post.getLink().indexOf("youtube") > -1){
					log.debug("getYoutubeURL(): url={}", post.getLink());
					return post.getLink();
				}
			}
		}
		log.debug("getYoutubeURL(): url=null");
		return null;
	}
}